package com.oss.config.database;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.oss.config.ThreadContext;
import com.oss.config.ThreadContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 插入或更新操作时, 通用字段无值时自动填充
 * @author chengqiang
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        if (Objects.isNull(metaObject.getValue("createTime"))) {
            this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }
        if (Objects.isNull(metaObject.getValue("updateTime"))) {
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }
        String userId = ThreadContext.getUserId();
        if (Objects.isNull(metaObject.getValue("creatorId"))) {
            this.setFieldValByName("creatorId", userId, metaObject);
        }
        if (Objects.isNull(metaObject.getValue("updatorId"))) {
            this.setFieldValByName("updatorId", userId, metaObject);
        }
        this.setFieldValByName("isDeleted", 0, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userId = ThreadContext.getUserId();
        if (Objects.isNull(metaObject.getValue("updateTime"))) {
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }
        this.setFieldValByName("updatorId", userId, metaObject);
    }
}
